package com.dunqi.gpm.cangxi.WeekReport.WeekChek;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.WeekReport.Model.WeekChekModel;
import com.dunqi.gpm.cangxi.WeekReport.Model.WeekPlan;
import com.dunqi.gpm.cangxi.WeekReport.OnListFragmentInteractionListener;
import com.dunqi.gpm.cangxi.WeekReport.WeekPlan.WeekPlanRecyclerViewAdapter;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.util.CommonUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class ItemWeekCheckFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int flag = 1;
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemWeekCheckFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static ItemWeekCheckFragment newInstance(int flag) {
        ItemWeekCheckFragment fragment = new ItemWeekCheckFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, flag);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            flag = getArguments().getInt(ARG_COLUMN_COUNT);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_itemweekcheck_list, container, false);

        srl = (SwipeRefreshLayout) view;
        srl.setOnRefreshListener(this);
        Context context = view.getContext();
        recyclerView = view.findViewById(R.id.list);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter = new WeekCheckRecyclerViewAdapter(flag, list, mListener));
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getData();
    }


    SwipeRefreshLayout srl;
    RecyclerView recyclerView;
    WeekCheckRecyclerViewAdapter adapter;
    List<WeekChekModel> list = new ArrayList<>();

    @SuppressLint("CheckResult")
    private void getData() {
        srl.setRefreshing(true);
        ApiFactory.getInstance()
                .projectWeeklyReportReviewList(CommonUtil.getDeviceId(), null, null)
                .compose(RxSchedulers.io_main())
                .subscribe(data -> {
                    if (data != null && data.getSize() > 0) {
                        if (data.getPageNum() == 1) {
                            list.clear();
                        }
//                        list.addAll(data.getList());
                        for (WeekChekModel item : data.getList()) {
                            if (flag == 1) {//待审核
                                if (item.getReportStatus() == null || item.getReportStatus() != 2) {
                                    list.add(item);
                                }
                            } else if (flag == 2) {//审核完成
                                if (item.getReportStatus() == 2) {
                                    list.add(item);
                                }
                            }
                        }
                        if (data.isHasNextPage()) {
                            adapter.loadMoreComplete();
                        } else {
                            adapter.loadMoreEnd();
                        }
                    } else {
                        adapter.loadMoreEnd();
                    }
                    srl.setRefreshing(false);
                }, throwable -> {
                    srl.setRefreshing(false);
                });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void action(String messageEvent) {
        if ("refresh_week_checklist".equals(messageEvent) && flag == 1) {
            getData();
        }
    }

    //    refresh_week_checklist
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh() {
        getData();
    }
}
